<template>
    <el-upload
        ref="UploadRef"
        :file-list="resourceFileList"
        :accept="types"
        :auto-upload="false"
        :multiple="true"
        :on-change="handleChange"
        :on-preview="handlePreview"
        :on-remove="removeFile"
    >
        <el-button type="primary">点我上传</el-button>
        <template #tip>
            <div class="el-upload__tip">
                格式为pdf或docx，不超过20M。
            </div>
        </template>
    </el-upload>
    <el-dialog v-model="show" title="预览" width="100%">
        <vue-office-docx
            v-if="isWord"
            :src="previewURL"
            @error="errorHandler"
        />
        <vue-office-pdf
            v-if="!isWord"
            :src="previewURL"
            @error="errorHandler"
        />
    </el-dialog>
</template>

<script setup>
//上传文件
import {ref} from "vue";
import VueOfficePdf from "@vue-office/pdf";
import VueOfficeDocx from "@vue-office/docx";
import '@vue-office/docx/lib/index.css'

const props = defineProps(["resourceFileList"])
const emits = defineEmits(["update:resourceFileList"])

const types = "application/pdf,application/docx,application/xml,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
const UploadRef = ref(null)
const handleChange = (file, fileList) => {
    console.log(file,fileList)
    //判断上传格式
    const typeArr = types.split(",")
    let flag = false
    for (const type of typeArr) {
        if (file.raw.type.includes(type)) {
            flag = true
            break
        }
    }
    if (!flag) {
        ElMessage.error("很抱歉您上传的文件格式不是pdf或docx")
        fileList.pop()
        return
    }
    if (file.raw.size / 1024 / 1024 > 20) {
        ElMessage.error("您上传的文件大小超过了20MB")
        fileList.pop()
        return;
    }
    emits("update:resourceFileList", fileList)
}
//预览框
let show = ref(false)
let previewURL = ref("")
let isWord = ref("")
const handlePreview = file => {
    //提供预览链接
    isWord.value = !file.raw.type.includes("pdf")
    previewURL.value = URL.createObjectURL(file.raw);
    show.value = true
}

const errorHandler = () => {
    ElMessage.error("文件加载错误,请稍后再试")
}
const removeFile = (file,fileList) => {
    emits("update:resourceFileList", fileList)
}
</script>

<style scoped>
:deep(.el-upload-list__item-name):hover{
    cursor: pointer;
}
</style>